package cn.jbolt.ai.core.chain.node.action.aichat;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.ai.core.chain.node.base.AppConfigConstant;
import cn.jbolt.ai.app.service.AiAppMessageService;
import cn.jbolt.ai.app.service.AiAppService;
import cn.jbolt.ai.app.service.AiAppSessionService;
import cn.jbolt.ai.core.chain.ChainContext;
import cn.jbolt.ai.core.chain.node.base.LlmConfig;
import cn.jbolt.ai.core.chain.node.base.BaseNode;
import cn.jbolt.ai.core.chain.node.base.RenderType;
import cn.jbolt.ai.core.chain.node.provider.EventNodeProvider;
import com.fasterxml.jackson.databind.JsonNode;
import com.jboltai.capability.model.JBoltAI;
import com.jboltai.event.ThinkStatus;
import com.jboltai.event.ai.aichat.AIChatEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;


@Component
public class AIChatNodeProvider extends BaseNode implements EventNodeProvider<AIChatEvent> {

    @Autowired
    private AiAppService aiAppService;
    @Autowired
    private AiAppSessionService aiAppSessionService;
    @Autowired
    private AiAppMessageService aiAppMessageService;
    private static final Logger logger = LoggerFactory.getLogger(AIChatNodeProvider.class);

    public AIChatEvent provide(JsonNode nodeConfig, ChainContext context) {
        AIChatEvent event = JBoltAI.chat();
        try {
            //根据配置初始化event
            LlmConfig config = LlmConfig.from(nodeConfig.get(AppConfigConstant.CONFIG_TYPE_LLM));
            super.configLlm(config, context, event);
            event.onSuccess((e, res) -> {
                if (Objects.equals(config.isOutputToResponse(), true)) {
                    //如果配置项要求 内容返回到响应里，那就输出，默认是true的
                    //构建相应信息
                    context.sendResponseMsg(res.getContent(), config.getRenderType() == null ? RenderType.markdown : config.getRenderType());
                }
            });
            event.setThinkingEnable(Objects.equals(config.getOutputThinking(), true));
            //输出思考过程
            event.onThinking((e, thinking, status) -> {
                if (status == ThinkStatus.START) {
                    context.sendThinking(ThinkStatus.START, thinking, null);
                } else if (status == ThinkStatus.RUNNING) {
                    context.sendThinking(ThinkStatus.RUNNING, thinking, null);
                } else if (status == ThinkStatus.COMPLETE) {
                    context.sendThinking(ThinkStatus.COMPLETE, thinking, e.getThinkDuration());
                }
                context.getResponseMsg().appendThinking(status, thinking);
            });
            event.onFail((e, error) -> {
                logger.error("ChatNode执行中发生异常,异常原因:{}", error.getFullMsg());
//                if (config.isOutputToResponse()) {
//                    //如果配置项要求 内容返回到响应里，那就输出
//                    //构建相应信息
//                    context.sendErrorMsg(error.getMsg());
//
//                }
            });

            event.onComplete((e) -> {
                switch (e.getState()) {
                    case SUCCESS:
                        //事件执行成功
                        if (StrUtil.isNotBlank(config.getOutputField())) {
                            //配置项要求，把结果输出到上下文
                            context.setAttr(config.getOutputField(), e.getResult());
                        }
                    case CANCEL:
                        if (Objects.equals(config.isPersistDb(), true)) {//成功或者取消 需要持久化数据
                            //把答案给存储
                            context.getResponseMsg().appendContent(e.getResult().getContent(), config.getRenderType());
                        }
                        break;
                    case FAIL:

                }
            });
            return event;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ChatNodeHandler process 异常,异常原因", e);
            context.sendErrorMsg("网络异常,请稍后重试....");
        }
        return null;
    }

}
